<?php

namespace App\V3\V3_1\Services;

use App\V3\V3_1\Models\AdminModel;
use App\V3\V3_1\Models\LogInStorageModel;
use App\V3\V3_1\Models\LogOutStorageModel;
use App\V3\V3_1\Models\LogPackageModel;
use App\V3\V3_1\Models\ModuleModel;
use App\V3\V3_1\Models\RoleSettingModel;
use App\V3\V3_1\Models\StorageBatchModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AdminService
{
    const SALT = 'storage';

    //获取被邀请人信息
    static public function inviteInfo($bindId)
    {
        $arr = [];
        if($bindId != 0) {
            $bindUserInfo = AdminModel::select('mobile')
                ->where('bind_id', $bindId)
                ->limit(3)
                ->orderBy('id', 'DESC')
                ->get();

            foreach($bindUserInfo as $value) {
                $arr[] = $value['mobile'];
            }
        }

        return $arr;
    }

    //子账号列表
    static public function userList($mainId, $data, $batchTitle)
    {
        return AdminModel::userList($mainId, $data, $batchTitle);
    }

    //检查子账户是否存在
    static public function checkUser($id)
    {
        if(!empty(AdminModel::where('id', $id)->first())) {
            return true;
        }
        else {
            return false;
        }
    }

    //审批人列表
    static public function approverList($mainId)
    {
        return AdminModel::getApproverList($mainId);
    }

    //重置指定子账号登录密码
    static public function resetPwd($data)
    {
        $isUpdate = AdminModel::where('id', $data['id'])->update([
            'password' => md5(md5('123456'.self::SALT)),
            'is_default_pwd' => 0
        ]);

        if($isUpdate !== false) {
            return true;
        }
        else {
            return false;
        }
    }

    //检查子账号是否已存在
    static public function checUserInfo($mainId, $data)
    {
        $userInfo = AdminModel::where([
            'username' => $data['username'],
            'delete_flag' => 0
        ])
            ->where('parent_id', '!=', 0)
            ->first();

        if(empty($userInfo)) {
            return true;
        }
        else {
            return false;
        }
    }

    //新建子账号
    static public function addUser($mainId, $data)
    {
        $mainInfo = AdminModel::where('id', $mainId)->first();

        $data['parent_id'] = $mainId;
        $randNo = rand(000000, 999999);

        do {
            $randNo = rand(000000, 999999);
        }
        while(!empty(AdminModel::where('parent_id', '!=', 0)
            ->where([
                'delete_flag' => 0,
                'newpwd' => $randNo
            ])->first()));

        $data['password'] = md5(md5('123456'.self::SALT));
        $data['newpwd'] = $randNo;
        $data['company_name'] = empty($mainInfo['company_name'])?'':$mainInfo['company_name'];
        $data['company_class'] = $mainInfo['company_class'];
        $data['created_at'] = time();
        $data['is_active'] = $data['status'];
        unset($data['status']);

        $userId = AdminModel::insertGetId($data);

        return ['id' => $userId];
    }

    //获取子账号权限信息
    static public function getUserPermission($mainId, $userInfo)
    {
        $parentModuleInfo = self::parentModuleInfo($mainId);

        $userFirstModuleArr = array_filter(explode(',', $userInfo['first_module']), function($v) { return $v !== ''; });
        $userSecondModuleArr = array_filter(explode(',', $userInfo['second_module']), function($v) { return $v !== ''; });

        // $moduleInfo = ModuleService::roleModuleList();

        $arr = [];
        foreach($parentModuleInfo as $key => $value)
        {
            $arr[$key]['id'] = $value['id'];
            $arr[$key]['module_name'] = $value['module_name'];
            $arr[$key]['type'] = $value['type'];
            $arr[$key]['sort'] = $value['sort'];
            $arr[$key]['module_img'] = empty($value['module_img'])?'':$value['module_img'];

            if(in_array($value['id'], $userFirstModuleArr)) {
                $arr[$key]['is_enable'] = 1;
            }
            else {
                $arr[$key]['is_enable'] = 0;
            }

            foreach($value['second_module'] as $k => $v) {
                $arr[$key]['second_module'][$k]['module_img'] = empty($v['module_img'])?'':$v['module_img'];
                if(in_array($v['id'], $userSecondModuleArr)) {
                    $arr[$key]['second_module'][$k]['is_enable'] = 1;
                }
                else {
                    $arr[$key]['second_module'][$k]['is_enable'] = 0;
                }

                $arr[$key]['second_module'][$k]['id'] = $v['id'];
                $arr[$key]['second_module'][$k]['module_name'] = $v['module_name'];
                $arr[$key]['second_module'][$k]['type'] = $v['type'];
                $arr[$key]['second_module'][$k]['sort'] = $v['sort'];
                $arr[$key]['second_module'][$k]['upper_module_id'] = $v['upper_module_id'];
            }
        }

        return $arr;
    }

    static private function parentModuleInfo($mainId)
    {
        $moduleInfo = AdminModel::select(
            'b.first_module',
            'b.second_module'
        )
            ->from('admin as a')
            ->leftJoin('role_setting as b', 'b.role_id', '=', 'a.admin_role')
            ->where('a.id', $mainId)->first();

        $firstModule = array_filter(explode(',', $moduleInfo['first_module']), function($v) { return $v !== ''; });
        $secondModule = array_filter(explode(',', $moduleInfo['second_module']), function($v) { return $v !== ''; });

        return ModuleModel::usefulPermission($firstModule, $secondModule);
    }

    //检查旧密码是否正确
    static public function checkPwd($userId, $data)
    {
        $userInfo = AdminModel::where('id', $userId)->first();

        if(md5(md5($data['old_pwd'].self::SALT)) != $userInfo['password']) {
            return false;
        }
        else {
            return true;
        }
    }

    //子账号修改登录密码
    static public function changePwd($userId, $data)
    {
        AdminModel::where('id', $userId)->update([
            'password' => md5(md5($data['new_pwd'].self::SALT)),
            'is_default_pwd' => 1
        ]);

        return true;
    }

    //个人中心
    static public function userCenter($userId, $mainId, $userType)
    {
        $data = AdminModel::select(
            'a.id',
            'username',
            'nickname',
            'mobile',
            'parent_id',
            'company_name',
            'company_class',
            'is_active',
            'bind_id',
            'invite_num',
            'b.name',
            'is_default_pwd',
            'openid as is_bind_openid',
            'wx_nickname',
            'out_storage_way',
            'batch_title',
            'first_module',
            'second_module'
        )
            ->from('admin as a')
            ->leftJoin('company_class as b', 'a.company_class', '=', 'b.id')
            ->where('a.id', $userId)->first();

        $startTime = strtotime(date('Y-m-d'));
        $endTime = strtotime(date('Y-m-d 23:59:59'));

        if($userId == $mainId) {
            $condition['main_id'] = ['EQ' => $mainId];
            unset($data['is_default_pwd']);
        }
        else {
            $condition['user_id'] = ['EQ' => $userId];
        }

        $mainInfo = AdminModel::select(
            'admin.*',
            'is_vip',
            'is_set_as_supplier',
            'is_share_customer',
            'is_in_experience',
            'is_end_experience',
            'vip_end_date',
            'is_share_express',
            'is_first_charge',
            'is_use_shelf',
            'is_use_serial',
            'account_storage',
            'file_total_size',
            'clear_watermark_or_not'
        )
            ->where([
                'admin.id' => $mainId,
            ])->leftJoin('admin_addendum as b', 'b.main_id', '=', 'admin.id')->first();
            if($mainInfo['is_vip'] > 0 && $mainInfo['invite_num'] < 3){
                $mainInfo['invite_num'] = 3;
            }
        $data['company_name'] = empty($mainInfo['company_name'])?"":$mainInfo['company_name'];
        $data['parent_id'] = $mainId;
        $data['bind_id'] = $mainInfo['bind_id'];
        $data['invite_num'] = $mainInfo['invite_num'];
        $data['invite_info'] = self::inviteInfo($mainId);
        $data['is_bind_openid'] = empty($data['is_bind_openid'])?0:1;
        $data['is_vip'] = $mainInfo['is_vip'];
        $data['is_set_as_supplier'] = $mainInfo['is_set_as_supplier'];
        $data['is_share_customer'] = $mainInfo['is_share_customer'];
        $data['is_in_experience'] = $mainInfo['is_in_experience'];
        $data['is_end_experience'] = $mainInfo['is_end_experience'];
        $data['vip_end_date'] = $mainInfo['vip_end_date'];
        $data['is_share_express'] = $mainInfo['is_share_express'];
        $data['is_first_charge'] = $mainInfo['is_first_charge'];
        $data['is_use_serial'] = $mainInfo['is_use_serial'];
        $data['account_storage'] = sprintf('%.2f', $mainInfo['account_storage'] / 1024 / 1024);
        $data['file_total_size'] = sprintf('%.2f', $mainInfo['file_total_size'] / 1024 / 1024);
        $data['clear_watermark_or_not'] = $mainInfo['clear_watermark_or_not'];
        $data['today_in_storage'] = LogInstorageModel::getTodayInCount($condition, $startTime, $endTime);//今日入库总数
        $data['today_out_storage'] = LogOutStorageModel::getTodayOutCount($condition, $startTime, $endTime);//今日出库
        $data['today_package'] = LogPackageModel::getTodayPackageCount($condition, $startTime, $endTime);//今日套餐出库总数
        $data['today_trans_storage'] = LogOutstorageModel::getTodayAllocateCount($condition, $startTime, $endTime);//今日调拨数量

        switch($userType) {
            case 0:
                $result = self::mainGetModelInfo($userId);
                break;
            default:
                $result = self::userGetModelInfo($userId);
        }

        $data['is_use_shelf'] = $mainInfo['is_use_shelf'];
        $data['is_main'] = $mainId == $userId?1:0;
        $data['module_info'] = $result;

        unset($data['first_module']);
        unset($data['second_module']);

        $data['field_list'] = DataFieldService::distinguishPermissionList($userId);

        return $data;
    }

    //查看被邀请人列表
    static public function inviteList($mainId, $data)
    {
        $result = AdminModel::select('nickname', 'mobile')->where('bind_id', $mainId)
            ->orderBy('id', 'DESC')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return $result;
    }

    static public function setPwd($data)
    {
        AdminModel::where('id', $data['id'])
            ->update([
                'password' => md5(md5($data['password'].self::SALT))
            ]);

        return true;
    }

    static public function transOutWay($mainId)
    {
        $mainInfo = AdminModel::where('id', $mainId)->first();

        DB::beginTransaction();

        try {
            //变更出库方式
            $updateData = [];
            if($mainInfo['out_storage_way'] == 0) {
                $updateData['out_storage_way'] = 1;
            }
            else {
                $updateData['out_storage_way'] = 0;
            }
            AdminModel::where('id', $mainId)->update($updateData);
            AdminModel::where('parent_id', $mainId)->update($updateData);

            $storageBatchInfo = StorageBatchModel::select('id')
                ->where('batch_left_num', '!=', 0)
                ->where('main_id', $mainId)->get()->toArray();

            $time = time();
            foreach($storageBatchInfo as $value) {
                $batchNo = $mainInfo['batch_title'].date('YmdHis', $time).mt_rand(1000, 9999).'0';

                do {
                    $batchNo = $mainInfo['batch_title'].date('YmdHis', $time).mt_rand(1000, 9999).'0';
                }
                while(!empty(StorageBatchModel::where('main_id', $mainId)
                    ->where('batch_no', $batchNo)->first()));

                StorageBatchModel::where('id', $value['id'])
                    ->update([
                        'batch_no' => $batchNo
                    ]);
            }

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }
        catch(\Exception $e) {
            DB::rollBack();
            Log::debug('转换出库方式异常:'.var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => '转换失败,请重试', 'data' => ''];
        }
    }

    private static function mainGetModelInfo(int $userId)
    {
        $adminInfo = AdminModel::getAccountInfo($userId);
        $roleInfo = RoleSettingModel::where('role_id', $adminInfo['admin_role'])->first();

        $userFirstModuleArr = array_filter(explode(',', $roleInfo['first_module']), function($v) { return $v !== ''; });
        $userSecondModuleArr = array_filter(explode(',', $roleInfo['second_module']), function($v) { return $v !== ''; });

        return self::moduleCommon($userFirstModuleArr, $userSecondModuleArr);
    }

    private static function userGetModelInfo(int $userId)
    {
        $userInfo = AdminModel::getAccountInfo($userId);
        $userFirstModuleArr = array_filter(explode(',', $userInfo['first_module']), function($v) { return $v !== ''; });
        $userSecondModuleArr = array_filter(explode(',', $userInfo['second_module']), function($v) { return $v !== ''; });

        return self::moduleCommon($userFirstModuleArr, $userSecondModuleArr);
    }

    private static function moduleCommon(array $userFirstModuleArr, array $userSecondModuleArr)
    {
        $firstModuleInfo = ModuleModel::select(
            'id',
            'module_name',
            'upper_module_id',
            'module_img',
            'type',
            'sort',
            'icon',
            'url1',
            'url2'
        )
            ->whereIn('id', $userFirstModuleArr)
            ->where('delete_flag', 0)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'DESC')
            ->get()->toArray();

        $secondModuleInfo = ModuleModel::select(
            'id',
            'module_name',
            'upper_module_id',
            'module_img',
            'type',
            'sort',
            'icon',
            'url1',
            'url2'
        )
            ->whereIn('id', $userSecondModuleArr)
            ->where('delete_flag', 0)
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'DESC')
            ->get()->toArray();

        foreach($firstModuleInfo as $key => $value) {
            foreach($secondModuleInfo as $k => $v) {
                if($value['id'] == $v['upper_module_id']) {
                    $firstModuleInfo[$key]['second_module'][] = $v;
                }
            }
        }

        return $firstModuleInfo;
    }
}
